package model

import (
	"common/helper"
	myredis "common/redis"
	"database/sql"
	"errors"
	"fmt"
	g "github.com/doug-martin/goqu/v9"
	"github.com/valyala/fasthttp"
	"strconv"
	"strings"
	"time"
)

type ReportPlatformTotalDataRet struct {
	TotalUser         int     `json:"total_user" db:"total_user"`                 // 会员量
	Deposit           float64 `json:"deposit" db:"deposit"`                       // 充值数量
	DepositNum        float64 `json:"deposit_num" db:"deposit_num"`               // 充值人数
	Withdraw          float64 `json:"withdraw" db:"withdraw"`                     // 充值数量
	WithdrawNum       float64 `json:"withdraw_num" db:"withdraw_num"`             // 提现人数
	Profit            float64 `json:"profit" db:"profit"`                         // 系统盈亏 充值数量-充值数量
	Running           float64 `json:"running" db:"running"`                       // 流水
	GameRound         int     `json:"game_round" db:"game_round"`                 // 游戏局数
	GameTax           float64 `json:"game_tax" db:"game_tax"`                     // 游戏税收
	GameWinlost       float64 `json:"game_winlost" db:"game_winlost"`             // 游戏赢亏
	GameRate          float64 `json:"game_rate" db:"game_rate"`                   // 游戏回报率
	UndepositWithdraw float64 `json:"undeposit_withdraw" db:"undeposit_withdraw"` // 未充提款
	UpScore           float64 `json:"up_score" db:"up_score"`                     // 上分数量
	Balance           float64 `json:"balance" db:"balance"`                       // 剩余金币
}

func ReportPlatformTotalData(ctx *fasthttp.RequestCtx) (ReportPlatformTotalDataRet, error) {

	where := "1=1"
	loginUser := GetLoginUser(ctx)
	if loginUser.Operator != "" {
		where += " and business_id=0 and operator_id=" + loginUser.Operator
	} else if loginUser.Businsess != "" {
		where += " and business_id=" + loginUser.Businsess
	} else {
		where += " and business_id=0"
	}
	table := "tbl_report_daily"
	data := ReportPlatformTotalDataRet{}

	//统计
	sfield := "ifnull(sum(deposit),0) deposit," +
		"ifnull(sum(withdraw),0) withdraw," +
		"ifnull(sum(running),0) running," +
		"ifnull(sum(game_round),0) game_round," +
		"ifnull(sum(game_tax),0) game_tax," +
		"ifnull(sum(running - game_winlost),0) game_winlost," +
		"ifnull(sum(first_deposit_num),0) deposit_num," +
		"ifnull(sum(withdraw_num),0) withdraw_num," +
		"ifnull(sum(up_score),0) up_score," +
		"ifnull(sum(undeposit_withdraw),0) undeposit_withdraw," +
		"ifnull(sum(new_user),0) total_user"
	query := "select " + sfield + " from " + table + " where " + where

	err := meta.MerchantDB.Get(&data, query)

	if err != nil && err != sql.ErrNoRows {
		return data, pushLog(fmt.Errorf("%s,[%s]", err.Error(), query), "数据库错误")
	}
	data.Profit = data.Deposit - data.Withdraw
	if data.Running == 0 {
		data.GameRate = 0
	} else {
		data.GameRate = (data.Running - data.GameWinlost) / data.Running * 100
	}

	gameRate := fmt.Sprintf("%.2f", data.GameRate)
	data.GameRate, _ = strconv.ParseFloat(gameRate, 64)

	//充值玩家 余额
	where = "1=1"

	if loginUser.Operator != "" {
		where += " and c.operator_id=" + loginUser.Operator
	} else if loginUser.Businsess != "" {
		where += " and c.business_id=" + loginUser.Businsess
	} else {

	}
	table = "tbl_member_balance"
	//join := "  join tbl_member_accu as b on b.uid=a.uid and b.deposit>0" //统计表
	join := "  join tbl_member_base as c on c.uid=a.uid and c.tester=1 " +
		"" //玩家表
	query = "select sum(a.brl)  from " + table + " as a " + join + " where " + where
	meta.MerchantDB.Get(&data.Balance, query)

	return data, nil
}

func ReportUserDailyList(param ReportDailyParam, ctx *fasthttp.RequestCtx) (ReportUserDailyRetData, error) {

	where := "1=1"
	oderBy := "created_at"
	oderType := "desc"
	if param.Uid > 0 {
		where += " and a.uid=" + strconv.Itoa(param.Uid)
	}
	if param.StartTime != "" {
		where += " and a.created_at>='" + param.StartTime + "'"
	}
	if param.EndTime != "" {
		where += " and a.created_at<='" + param.EndTime + "'"
	}
	if param.OperatorId != "" {
		where += " and c.id=" + param.OperatorId
	}
	if param.BusinessId != "" {
		where += " and d.id=" + param.BusinessId
	}

	loginUser := GetLoginUser(ctx)
	if loginUser.Operator != "" {
		where += " and c.id=" + loginUser.Operator
	}
	if loginUser.Businsess != "" {
		where += " and d.id=" + loginUser.Businsess
	}
	if param.OderBY != "" {
		oderBy = param.OderBY
	}
	if param.OderType != "" {
		oderType = param.OderType
	}
	order := oderBy + " " + oderType
	join := " left join tbl_member_base as b on b.uid=a.uid"          //玩家表
	join += " left join tbl_operator_info as c on c.id=b.operator_id" //渠道表
	join += " left join tbl_business_info as d on d.id=b.business_id" //业务员表

	data := ReportUserDailyRetData{}
	offset := (param.Page - 1) * param.PageSize
	if param.Page >= 1 {
		count := "select count(1) from tbl_report_user_daily as a " + join + " where " + where

		err := meta.MerchantDB.Get(&data.T, count)
		if err != nil {
			return data, pushLog(fmt.Errorf("%s,[%s]", err.Error(), count), "数据库错误")
		}

		if data.T == 0 {
			return data, nil
		}
	}
	field := "a.uid,a.deposit,a.first_deposit,a.withdraw,a.running,a.running,a.game_round,(a.game_winlost - a.running) game_winlost,a.game_tax,a.proxy_invite_bonus,a.accu_deposit_bonus,a.week_lost_return,a.week_bet_return,a.week_deposit_return,a.week_commi_return,,a.app_download_bonus,a.created_at," +
		"ifnull(b.username,'') username," +
		"ifnull(c.id,'') operator_id," +
		"ifnull(c.operator_name,'') operator_name," +
		"ifnull(d.id,'') business_id," +
		"ifnull(d.account_name,'') as business_name"
	query := "select " + field + " from tbl_report_user_daily  as a " + join + " where " + where + " order by " + order + " limit " + strconv.Itoa(param.PageSize) + " offset " + strconv.Itoa(offset)

	err := meta.MerchantDB.Select(&data.D, query)
	if err != nil && err != sql.ErrNoRows {
		return data, pushLog(fmt.Errorf("%s,[%s]", err.Error(), query), "数据库错误")
	}
	//统计
	sfield := "ifnull(sum(deposit),0) deposit," +
		"ifnull(sum(withdraw),0) withdraw," +
		"ifnull(sum(running),0) running," +
		"ifnull(sum(game_round),0) game_round," +
		"ifnull(sum(game_tax),0) game_tax," +
		"ifnull(sum(game_winlost - running),0) game_winlost," +
		"ifnull(sum(accu_deposit_bonus),0) accu_deposit_bonus," +
		"ifnull(sum(week_lost_return),0) week_lost_return," +
		"ifnull(sum(week_bet_return),0) week_bet_return," +
		"ifnull(sum(week_deposit_return),0) week_deposit_return," +
		"ifnull(sum(week_commi_return),0) week_commi_return," +
		"ifnull(sum(app_download_bonus),0) app_download_bonus," +
		"ifnull(sum(proxy_invite_bonus),0) proxy_invite_bonus"
	query = "select " + sfield + " from tbl_report_user_daily  as a " + join + " where " + where

	err = meta.MerchantDB.Get(&data.S, query)

	if err != nil && err != sql.ErrNoRows {
		return data, pushLog(fmt.Errorf("%s,[%s]", err.Error(), query), "数据库错误")
	}
	return data, nil
}

func ReportPlatformDailyList(param ReportDailyParam, ctx *fasthttp.RequestCtx) (ReportDailyRetData, error) {
	data := ReportDailyRetData{}
	where := "1=1"
	oderBy := "created_at"
	oderType := "desc"
	if param.Uid > 0 {
		where += " and a.uid=" + strconv.Itoa(param.Uid)
	}
	if param.StartTime != "" {
		where += " and a.created_at>='" + param.StartTime + "'"
	}
	if param.EndTime != "" {
		where += " and a.created_at<='" + param.EndTime + "'"
	}

	if param.OperatorId != "" {
		if param.IsBusiness == 1 {
			where += " and a.operator_id=" + param.OperatorId
		} else {
			where += " and a.business_id=0 and a.operator_id=" + param.OperatorId
		}
	}
	if param.BusinessId != "" {
		where += " and a.business_id=" + param.BusinessId
	}
	if param.OderBY != "" {
		oderBy = param.OderBY
	}
	if param.OderType != "" {
		oderType = param.OderType
	}
	order := oderBy + " " + oderType
	table := "tbl_report_daily"

	field := "a.*,(a.running-a.game_winlost) as system_profit,(CASE WHEN a.running=0 THEN 0 ELSE (a.game_winlost)*100/a.running END) as game_rate,ifnull(c.operator_name,'') operator_name,ifnull(d.account_name,'') business_name"
	join := " left join tbl_operator_info as c on c.id=a.operator_id" //渠道表
	join += " left join tbl_business_info as d on d.id=a.business_id" //业务员表

	loginUser := GetLoginUser(ctx)
	if loginUser.Operator != "" {
		if param.IsBusiness == 1 {
			//渠道查询业务员日况
			where += " and a.business_id>0 and a.operator_id=" + loginUser.Operator
		} else {
			where += " and a.business_id=0 and a.operator_id=" + loginUser.Operator
		}
	} else if loginUser.Businsess != "" {
		where += " and a.business_id in(" + GetBusinessTeam(loginUser.Businsess, loginUser.Businsess) + ")"
	} else {
		//总后台的日况，是所有渠道相加
		if param.IsOperator == 0 && param.IsBusiness == 0 {
			sumfield := "created_at,ifnull(sum(deposit_num),0) deposit_num," +
				"ifnull(sum(deposit),0) deposit," +
				"ifnull(sum(first_deposit_num),0) first_deposit_num," +
				"ifnull(sum(first_deposit),0) first_deposit," +
				"ifnull(sum(withdraw_num),0) withdraw_num," +
				"ifnull(sum(withdraw),0) withdraw," +
				"ifnull(sum(running),0) running," +
				"ifnull(sum(game_round),0) game_round," +
				"ifnull(sum(game_tax),0) game_tax," +
				"ifnull(sum(game_winlost),0) game_winlost," +
				"ifnull(sum(new_user),0) new_user," +
				"ifnull(sum(valid_num),0) valid_num," +
				"ifnull(sum(up_score),0) up_score," +
				"ifnull(sum(active_user),0) active_user," +
				"ifnull(sum(accu_deposit_bonus),0) accu_deposit_bonus," +
				"ifnull(sum(week_lost_return),0) week_lost_return," +
				"ifnull(sum(week_bet_return),0) week_bet_return," +
				"ifnull(sum(week_deposit_return),0) week_deposit_return," +
				"ifnull(sum(week_commi_return),0) week_commi_return," +
				"ifnull(sum(daily_bet_return),0) daily_bet_return," +
				"ifnull(sum(app_download_bonus),0) app_download_bonus," +
				"ifnull(sum(undeposit_withdraw),0) undeposit_withdraw," +
				"ifnull(sum(enable_first_deposit_to_parent),0) enable_first_deposit_to_parent," +
				"ifnull(sum(enable_recharge_share),0) enable_recharge_share," +
				"ifnull(sum(proxy_invite_bonus),0) proxy_invite_bonus"
			table = "(select " + sumfield + " from tbl_report_daily where business_id=0 and operator_id>0 group by created_at)"
			join = ""
			field = "a.*,(a.running-a.game_winlost) as system_profit,(CASE WHEN a.running=0 THEN 0 ELSE (a.game_winlost)*100/a.running END) as game_rate"
		}

		if param.IsOperator != 0 {
			//总后台查询渠道日况
			where += " and a.business_id=0 and a.operator_id>0"
		}
		if param.IsBusiness != 0 {
			//总后台查询业务员日况
			where += " and a.business_id>0"
		}
	}

	offset := (param.Page - 1) * param.PageSize
	if param.Page >= 1 {
		count := "select count(1) from " + table + " as a  where " + where

		err := meta.MerchantDB.Get(&data.T, count)
		if err != nil {
			return data, pushLog(fmt.Errorf("%s,[%s]", err.Error(), count), "数据库错误")
		}

		if data.T == 0 {
			return data, nil
		}
	}

	query := "select " + field + " from " + table + " as a " + join + " where " + where + " order by " + order + " limit " + strconv.Itoa(param.PageSize) + " offset " + strconv.Itoa(offset)

	err := meta.MerchantDB.Select(&data.D, query)

	if err != nil && err != sql.ErrNoRows {
		return data, pushLog(fmt.Errorf("%s,[%s]", err.Error(), query), "数据库错误")
	}
	for key, value := range data.D {
		GameRate := fmt.Sprintf("%.2f", value.GameRate)
		data.D[key].GameRate, _ = strconv.ParseFloat(GameRate, 64)
	}
	//统计
	sfield := "ifnull(sum(deposit_num),0) deposit_num," +
		"ifnull(sum(deposit),0) deposit," +
		"ifnull(sum(first_deposit_num),0) first_deposit_num," +
		"ifnull(sum(first_deposit),0) first_deposit," +
		"ifnull(sum(withdraw_num),0) withdraw_num," +
		"ifnull(sum(withdraw),0) withdraw," +
		"ifnull(sum(running),0) running," +
		"ifnull(sum(game_round),0) game_round," +
		"ifnull(sum(game_tax),0) game_tax," +
		"ifnull(sum(valid_num),0) valid_num," +
		"ifnull(sum(game_winlost),0) game_winlost," +
		"ifnull(sum(new_user),0) new_user," +
		"ifnull(sum(valid_num),0) valid_num," +
		//"ifnull(sum(active_user),0) active_user," +
		"ifnull(sum(a.running - game_winlost),0) system_profit," +
		"ifnull(sum(accu_deposit_bonus),0) accu_deposit_bonus," +
		"ifnull(sum(week_lost_return),0) week_lost_return," +
		"ifnull(sum(week_bet_return),0) week_bet_return," +
		"ifnull(sum(week_deposit_return),0) week_deposit_return," +
		"ifnull(sum(week_commi_return),0) week_commi_return," +
		"ifnull(sum(daily_bet_return),0) daily_bet_return," +
		"ifnull(sum(app_download_bonus),0) app_download_bonus," +
		"ifnull(sum(undeposit_withdraw),0) undeposit_withdraw," +
		"ifnull(sum(enable_first_deposit_to_parent),0) enable_first_deposit_to_parent," +
		"ifnull(sum(enable_recharge_share),0) enable_recharge_share," +
		"ifnull(sum(proxy_invite_bonus),0) proxy_invite_bonus"
	query = "select " + sfield + " from " + table + " as a where " + where

	err = meta.MerchantDB.Get(&data.S, query)

	if err != nil && err != sql.ErrNoRows {
		return data, pushLog(fmt.Errorf("%s,[%s]", err.Error(), query), "数据库错误")
	}
	if (data.S).Running == 0 {
		(data.S).GameRate = 0
	} else {
		(data.S).GameRate = ((data.S).GameWinlost) / (data.S).Running * 100
		gameRate := fmt.Sprintf("%.2f", (data.S).GameRate)
		(data.S).GameRate, _ = strconv.ParseFloat(gameRate, 64)

	}
	return data, nil
}

func ReportGameDailyList(param GameDailyParam, ctx *fasthttp.RequestCtx) (ReportGameDailyRetData, error) {
	where := "1=1"
	oderBy := "created_at"
	oderType := "desc"
	if param.PlatformId > 0 {
		where += " and a.platform_id=" + strconv.Itoa(param.PlatformId)
	}
	if param.StartTime != "" {
		where += " and a.created_at>='" + param.StartTime + "'"
	}
	if param.EndTime != "" {
		where += " and a.created_at<='" + param.EndTime + "'"
	}
	if param.OperatorId != "" {
		if param.IsBusiness == 1 {
			where += " and a.operator_id=" + param.OperatorId
		} else {
			where += " and a.business_id=0 and a.operator_id=" + param.OperatorId
		}
	}
	if param.BusinessId != "" {
		where += " and a.business_id=" + param.BusinessId
	}
	if param.OderBY != "" {
		oderBy = param.OderBY
	}
	if param.OderType != "" {
		oderType = param.OderType
	}
	table := "tbl_report_game_daily"
	loginUser := GetLoginUser(ctx)
	order := oderBy + " " + oderType
	field := "a.*,(a.running - a.game_winlost) as system_profit,(a.sandbag_running - a.sandbag_game_winlost) as sandbag_profit,(CASE WHEN a.running=0 THEN 0 ELSE (a.game_winlost)*100/a.running END) as game_rate,ifnull(b.name,'') game_name,ifnull(c.operator_name,'') operator_name,ifnull(d.account_name,'') business_name,ifnull(b.name,'') game_name"

	join := " left join tbl_platforms as b on b.id=a.platform_id"     //游戏表
	join += " left join tbl_operator_info as c on c.id=a.operator_id" //渠道表
	join += " left join tbl_business_info as d on d.id=a.business_id" //业务员表
	if loginUser.Operator != "" {
		if param.IsBusiness == 1 {
			//渠道查询业务员游戏日报
			where += " and a.business_id>0 and a.operator_id=" + loginUser.Operator
		} else {
			where += " and a.business_id=0 and a.operator_id=" + loginUser.Operator
		}
	} else if loginUser.Businsess != "" {
		where += " and a.business_id in(" + GetBusinessTeam(loginUser.Businsess, loginUser.Businsess) + ")"
	} else {
		//总后台的游戏日报
		if param.IsOperator == 0 && param.IsBusiness == 0 {
			sumfield := "platform_id,created_at," +
				"ifnull(sum(running),0) running," +
				"ifnull(sum(sandbag_running),0) sandbag_running," +
				"ifnull(sum(sandbag_game_winlost),0) sandbag_game_winlost," +
				"ifnull(sum(game_round),0) game_round," +
				"ifnull(sum(game_tax),0) game_tax," +
				"ifnull(sum(game_winlost),0) game_winlost"
			table = "(select " + sumfield + " from tbl_report_game_daily where business_id=0 and operator_id>0 group by platform_id,created_at)"
			join = "left join tbl_platforms as b on b.id=a.platform_id"
			field = "a.*,(a.running - a.game_winlost) as system_profit,(a.sandbag_running - a.sandbag_game_winlost) as sandbag_profit,(CASE WHEN a.running=0 THEN 0 ELSE (a.game_winlost)*100/a.running END) as game_rate,ifnull(b.name,'') game_name"
		}

		if param.IsOperator != 0 {
			//总后台查询渠道游戏日报
			where += " and a.business_id=0 and a.operator_id>0"
		}
		if param.IsBusiness != 0 {
			//总后台查询业务员游戏日报
			where += " and a.business_id>0"
		}
	}

	data := ReportGameDailyRetData{}
	offset := (param.Page - 1) * param.PageSize
	if param.Page >= 1 {
		count := "select count(1) from " + table + " as a  where " + where

		err := meta.MerchantDB.Get(&data.T, count)
		if err != nil {
			return data, pushLog(fmt.Errorf("%s,[%s]", err.Error(), count), "数据库错误")
		}

		if data.T == 0 {
			return data, nil
		}
	}

	query := "select " + field + " from " + table + " as a " + join + " where " + where + " order by " + order + " limit " + strconv.Itoa(param.PageSize) + " offset " + strconv.Itoa(offset)

	err := meta.MerchantDB.Select(&data.D, query)

	if err != nil && err != sql.ErrNoRows {
		return data, pushLog(fmt.Errorf("%s,[%s]", err.Error(), query), "数据库错误")
	}
	for key, value := range data.D {
		GameRate := fmt.Sprintf("%.2f", value.GameRate)
		data.D[key].GameRate, _ = strconv.ParseFloat(GameRate, 64)
	}

	//统计
	sfield := "ifnull(sum(running),0) running," +
		"ifnull(sum(game_round),0) game_round," +
		"ifnull(sum(game_tax),0) game_tax," +
		"ifnull(sum(running - game_winlost),0) system_profit," +
		"ifnull(sum(sandbag_running - sandbag_game_winlost),0) sandbag_profit," +
		"ifnull(sum(game_winlost),0) game_winlost"
	query = "select " + sfield + " from " + table + " as a where " + where

	err = meta.MerchantDB.Get(&data.S, query)

	if err != nil && err != sql.ErrNoRows {
		return data, pushLog(fmt.Errorf("%s,[%s]", err.Error(), query), "数据库错误")
	}
	if (data.S).Running == 0 {
		(data.S).GameRate = 0
	} else {
		(data.S).GameRate = (data.S).GameWinlost / (data.S).Running * 100
		gameRate := fmt.Sprintf("%.2f", (data.S).GameRate)
		(data.S).GameRate, _ = strconv.ParseFloat(gameRate, 64)

	}
	return data, nil
}

// 玩家游戏盈亏结算
func ReportUserGameDailyList(param UserGameDailyParam, ctx *fasthttp.RequestCtx) (ReportUserGameDailyRetData, error) {
	data := ReportUserGameDailyRetData{}

	where := " cash_type in(" + strconv.Itoa(helper.TransactionBet) + "," + strconv.Itoa(helper.TransactionPayout) + ")"
	if param.PlatformId > 0 {
		where += " and platform_id=" + strconv.Itoa(param.PlatformId)
	}
	if param.StartTime != "" {
		StartTime, _ := helper.TimeToLocMs(param.StartTime, loc)
		where += " and created_at>='" + strconv.FormatInt(StartTime, 10) + "'"
	}
	if param.EndTime != "" {
		EndTime, _ := helper.TimeToLocMs(param.EndTime, loc)
		where += " and created_at<='" + strconv.FormatInt(EndTime, 10) + "'"
	}
	table := "(select uid,sum(case when cash_type=301 then 1 else 0 end) as game_round,-sum(case when cash_type=301 then amount else 0 end) as running,sum(case when cash_type=302 then amount else 0 end) as game_winlost from tbl_balance_transaction where " + where + " group by uid)"

	newWhere := "1=1"
	loginUser := GetLoginUser(ctx)
	if loginUser.Operator != "" {
		newWhere += " and b.operator_id=" + loginUser.Operator
	} else if loginUser.Businsess != "" {
		newWhere += " and b.business_id=" + loginUser.Businsess
	}
	oderBy := "(a.running - a.game_winlost)"
	oderType := "asc"
	if param.OderBY != "" {
		if param.OderBY == "system_profit" {
			param.OderBY = "(a.running - a.game_winlost)"
		}
		if param.OderBY == "game_rate" {
			param.OderBY = "(CASE WHEN a.running=0 THEN 0 ELSE (a.game_winlost)*100/a.running END)"
		}
		oderBy = param.OderBY
	}
	if param.OderType != "" {
		oderType = param.OderType
	}
	join := " left join tbl_member_base as   b on b.uid=a.uid" //玩家表
	order := oderBy + " " + oderType
	offset := (param.Page - 1) * param.PageSize
	if param.Page >= 1 {
		count := "select count(1) from " + table + " as a " + join + " where " + newWhere

		err := meta.MerchantDB.Get(&data.T, count)
		if err != nil {
			return data, pushLog(fmt.Errorf("%s,[%s]", err.Error(), count), "数据库错误")
		}

		if data.T == 0 {
			return data, nil
		}
	}
	field := "a.*,(a.running - a.game_winlost) as system_profit,(CASE WHEN a.running=0 THEN 0 ELSE (a.game_winlost)*100/a.running END) as game_rate"

	query := "select " + field + "  from " + table + " as a " + join + " where " + newWhere + " order by " + order + " limit " + strconv.Itoa(param.PageSize) + " offset " + strconv.Itoa(offset)

	err := meta.MerchantDB.Select(&data.D, query)

	if err != nil && err != sql.ErrNoRows {
		return data, pushLog(fmt.Errorf("%s,[%s]", err.Error(), query), "数据库错误")
	}

	for key, value := range data.D {
		GameRate := fmt.Sprintf("%.2f", value.GameRate)
		data.D[key].GameRate, _ = strconv.ParseFloat(GameRate, 64)
	}
	return data, nil
}

// 游戏生态监控
func ReportGameMonitorList(param UserGameMonitorParam, ctx *fasthttp.RequestCtx) (ReportUserGameMonitorRetData, error) {
	data := ReportUserGameMonitorRetData{}

	where := "1=1"
	oderBy := "created_at"
	oderType := "desc"

	if param.StartTime != "" {
		where += " and a.created_at>='" + param.StartTime + "'"
	}
	if param.EndTime != "" {
		where += " and a.created_at<='" + param.EndTime + "'"
	}
	if param.Ctype == 1 {
		where += " and c.deposit>0"
	}
	if param.Ctype == 2 {
		where += " and c.deposit=0"
	}
	if param.Ctype == 3 {
		where += " and a.first_deposit>0"
	}
	loginUser := GetLoginUser(ctx)
	if loginUser.Operator != "" {
		where += " and b.id=" + loginUser.Operator
	}
	if loginUser.Businsess != "" {
		where += " and b.id=" + loginUser.Businsess
	}
	if param.OderBY != "" {
		oderBy = param.OderBY
	}
	if param.OderType != "" {
		oderType = param.OderType
	}
	order := oderBy + " " + oderType
	join := ""
	//join += " left join tbl_member_base as b on b.uid=a.uid"          //玩家表
	join += " left join tbl_member_accu as c on c.uid=a.uid" //玩家统计表

	table := "(select created_at,sum(a.deposit) as deposit,sum(a.withdraw) as withdraw,sum(a.running) as running,sum(a.game_round) as game_round,sum(a.game_winlost) as game_winlost,sum(a.game_tax) as game_tax,(CASE WHEN sum(a.running)=0 THEN 0 ELSE (sum(a.game_winlost))*100/sum(a.running) END) as game_rate,(sum(a.running) - sum(a.game_winlost)) as system_profit from tbl_report_user_daily as a " + join + " where " + where + " group by created_at) as tb"
	offset := (param.Page - 1) * param.PageSize
	if param.Page >= 1 {
		count := "select count(1) from " + table

		err := meta.MerchantDB.Get(&data.T, count)
		if err != nil {
			return data, pushLog(fmt.Errorf("%s,[%s]", err.Error(), count), "数据库错误")
		}

		if data.T == 0 {
			return data, nil
		}
	}
	field := "*"
	query := "select " + field + " from " + table + " order by " + order + " limit " + strconv.Itoa(param.PageSize) + " offset " + strconv.Itoa(offset)

	err := meta.MerchantDB.Select(&data.D, query)
	if err != nil && err != sql.ErrNoRows {
		return data, pushLog(fmt.Errorf("%s,[%s]", err.Error(), query), "数据库错误")
	}
	for key, value := range data.D {
		GameRate := fmt.Sprintf("%.2f", value.GameRate)
		data.D[key].GameRate, _ = strconv.ParseFloat(GameRate, 64)
	}
	return data, nil
}

// 留存报表
func ReportUserRemainList(param UserRemainParam, ctx *fasthttp.RequestCtx) (UserRemainRetData, error) {
	data := UserRemainRetData{}
	data.D = make(map[int]UserRemainData)
	where := "1=1"

	if param.Date == "" {
		param.Date = time.Now().Format("2006-01-02")
	}
	st, _ := time.ParseInLocation("2006-01-02", param.Date, loc)
	if param.OperatorId != "" {
		where += " and b.operator_id=" + param.OperatorId
	}
	queryUser := ""
	//注册
	if param.Ctype == 1 {
		StartTime := st.Unix()
		EndTime := StartTime + 86400
		where += " and b.created_at>='" + strconv.FormatInt(StartTime, 10) + "'"
		where += " and b.created_at<'" + strconv.FormatInt(EndTime, 10) + "'"
		queryUser = "select b.uid from tbl_member_base as b  where b.tester=1 and " + where
	}
	//充值
	if param.Ctype == 2 {
		where += " and a.created_at='" + param.Date + "'"
		where += " and a.deposit>0"
		queryUser = "select a.uid from tbl_report_user_daily as a join tbl_member_base as b on a.uid=b.uid and " + where
	}
	//首充
	if param.Ctype == 3 {
		where += " and a.created_at='" + param.Date + "'"
		where += " and a.first_deposit>0"
		queryUser = "select a.uid from tbl_report_user_daily as a join tbl_member_base as b on a.uid=b.uid where " + where
	}
	uids := []string{}
	meta.MerchantDB.Select(&uids, queryUser)
	data.T = len(uids)

	//count := "select count(1) from (" + queryUser + ") as tb"
	//err := meta.MerchantDB.Get(&data.T, count)
	//if err != nil {
	//	return data, pushLog(fmt.Errorf("%s,[%s]", err.Error(), count), "数据库错误")
	//}
	if data.T == 0 {
		return data, nil
	}
	strUids := strings.Join(uids, ",")
	arr := []int{1, 2, 3, 5, 7, 15, 30}
	for _, val := range arr {
		newUserRemainData := UserRemainData{}
		date := st.AddDate(0, 0, val).Format("2006-01-02")
		field := "ifnull(count(is_login),0) is_login," +
			"ifnull(sum(case when deposit>0 then 1 else 0 end),0) as deposit," +
			"ifnull(sum(case when withdraw>0 then 1 else 0 end),0) as withdraw," +
			"ifnull(sum(case when running>0 then 1 else 0 end),0) as running"
		//query := "select " + field + "  from tbl_report_user_daily as aa join (" + queryUser + ") as bb on aa.uid=bb.uid where created_at='" + date + "'"
		query := "select " + field + "  from tbl_report_user_daily  where created_at='" + date + "' and uid in(" + strUids + ")"
		meta.MerchantDB.Get(&newUserRemainData, query)
		(data.D)[val] = newUserRemainData
	}
	return data, nil
}

func WeekCommiList(param CommonParam, ctx *fasthttp.RequestCtx) (WeekCommiRetData, error) {
	data := WeekCommiRetData{}
	where := "1=1"
	oderBy := "create_time"
	oderType := "desc"

	if param.OderBY != "" {
		oderBy = param.OderBY
	}
	if param.OderType != "" {
		oderType = param.OderType
	}

	loginUser := GetLoginUser(ctx)
	if loginUser.Operator != "" {
		where += " and c.id=" + loginUser.Operator
	}
	if loginUser.Businsess != "" {
		where += " and d.id=" + loginUser.Businsess
	}

	join := " left join tbl_member_base as b on b.uid=a.uid"          //玩家表
	join += " left join tbl_operator_info as c on c.id=b.operator_id" //渠道表
	join += " left join tbl_business_info as d on d.id=b.business_id" //业务员表

	order := oderBy + " " + oderType

	offset := (param.Page - 1) * param.PageSize
	if param.Page >= 1 {
		count := "select count(1) from tbl_member_return as a " + join + " where " + where

		err := meta.MerchantDB.Get(&data.T, count)
		if err != nil {

			return data, pushLog(fmt.Errorf("%s,[%s]", err.Error(), count), "数据库错误")
		}

		if data.T == 0 {
			return data, nil
		}
	}

	field := "a.*," +
		"ifnull(b.username,'') username," +
		"ifnull(c.id,'') operator_id," +
		"ifnull(c.operator_name,'') operator_name," +
		"ifnull(d.id,'') business_id," +
		"ifnull(d.account_name,'') as business_name"
	query := "select " + field + " from tbl_member_return  as a " + join + " where " + where + " order by " + order + " limit " + strconv.Itoa(param.PageSize) + " offset " + strconv.Itoa(offset)

	err := meta.MerchantDB.Select(&data.D, query)
	if err != nil && err != sql.ErrNoRows {

		return data, pushLog(fmt.Errorf("%s,[%s]", err.Error(), query), "数据库错误")
	}

	//统计
	sfield := "ifnull(sum(a.week_deposit_return),0) week_deposit_return," +
		"ifnull(sum(a.week_bet_return),0) week_bet_return," +
		"ifnull(sum(a.week_proxy_commi_return),0) week_proxy_commi_return," +
		"ifnull(sum(a.week_lost_return),0) week_lost_return"
	query = "select " + sfield + " from tbl_member_return as a " + join + " where " + where

	err = meta.MerchantDB.Get(&data.S, query)

	if err != nil && err != sql.ErrNoRows {
		return data, pushLog(fmt.Errorf("%s,[%s]", err.Error(), query), "数据库错误")
	}
	return data, nil
}

func WeeklyComiList(param WeeklyCommiParam, ctx *fasthttp.RequestCtx) (WeeklyCommiRetData, error) {
	data := WeeklyCommiRetData{}
	table := "tbl_member_base"
	where := "1=1"
	oderBy := "uid"
	oderType := "desc"

	//本周开始时间戳
	now := time.Now()
	weekStart := now.AddDate(0, 0, -int(now.Weekday())+1)
	weekStartTimestamp := weekStart.Unix()

	weekStartDate := weekStart.Format("2006-01-02")

	lastWeekStartTimestamp := weekStartTimestamp - 7*86400
	lastWeekStartDate := time.Unix(lastWeekStartTimestamp, 0).Format("2006-01-02")
	//lastWeekEndTimestamp := weekStartTimestamp
	lastWeekEndDate := weekStartDate
	query1, query2, query3, query4, query5 := "", "", "", "", ""

	if param.Ctype == 1 {
		//获取上周返佣
		query1 = "select uid,sum(week_commi_return) last_week_commi from tbl_report_user_daily where " + " created_at>='" + weekStartDate + "' group by uid"
		//获取上周未领取返佣
		query2 = "select uid,week_proxy_commi_return last_week_uncommi from tbl_member_return"
		//获取已领取返佣
		query3 = "select uid,week_commi_return receive_commi from tbl_member_accu"

		//获取本周下级充值
		query4 = "select uid,sum(deposit_commi_return) this_week from tbl_report_proxy_daily where level=1 and " + " created_at>='" + weekStartDate + "' group by uid"
		//获取上周下级充值
		query5 = "select uid,sum(deposit_commi_return) last_week from tbl_report_proxy_daily where level=1 and " + " created_at>='" + lastWeekStartDate + "' and created_at<'" + lastWeekEndDate + "' group by uid"
	}
	if param.Ctype == 2 {
		//获取上周返佣
		query1 = "select uid,sum(week_deposit_return) last_week_commi from tbl_report_user_daily where " + " created_at>='" + weekStartDate + "' group by uid"
		//获取上周未领取返佣
		query2 = "select uid,week_deposit_return last_week_uncommi from tbl_member_return"
		//获取获取已领取返佣
		query3 = "select uid,week_deposit_return receive_commi from tbl_member_accu"

		//获取本周充值
		query4 = "select uid,sum(deposit) this_week from tbl_report_user_daily where " + " created_at>='" + weekStartDate + "' group by uid"
		//获取上周充值
		query5 = "select uid,sum(deposit) last_week from tbl_report_user_daily where " + " created_at>='" + lastWeekStartDate + "' and created_at<'" + lastWeekEndDate + "' group by uid"
	}
	if param.Ctype == 3 {
		//获取上周返佣
		query1 = "select uid,sum(week_lost_return) last_week_commi from tbl_report_user_daily where " + " created_at>='" + weekStartDate + "' group by uid"
		//获取上周未领取返佣
		query2 = "select uid,week_lost_return last_week_uncommi from tbl_member_return"
		//获取已领取返佣
		query3 = "select uid,week_lost_return receive_commi from tbl_member_accu"

		//获取本周亏损
		query4 = "select uid,CONCAT(sum(deposit),'/',sum(withdraw))  this_week from tbl_report_user_daily where " + " created_at>='" + weekStartDate + "' group by uid"
		//获取上周亏损
		query5 = "select uid,CONCAT(sum(deposit),'/',sum(withdraw))  last_week from tbl_report_user_daily where" + " created_at>='" + lastWeekStartDate + "' and created_at<'" + lastWeekEndDate + "' group by uid"
	}
	if param.Ctype == 4 {
		//获取上周返佣
		query1 = "select uid,sum(week_bet_return) last_week_commi from tbl_report_user_daily where " + " created_at>='" + weekStartDate + "' group by uid"
		//获取上周未领取返佣
		query2 = "select uid,week_bet_return last_week_uncommi from tbl_member_return"
		//获取已领取返佣
		query3 = "select uid,week_bet_return receive_commi from tbl_member_accu"

		//获取本周投注
		query4 = "select uid,sum(valid_waged) this_week from tbl_report_user_daily where " + " created_at>='" + weekStartDate + "' group by uid"
		//获取上周投注
		query5 = "select uid,sum(valid_waged) last_week from tbl_report_user_daily where " + " created_at>='" + lastWeekStartDate + "' and created_at<'" + lastWeekEndDate + "' group by uid"
	}
	//日活动数据
	dailyStart := now.Format("2006-01-02")
	lastDailyStartDate := now.AddDate(0, 0, -1).Format("2006-01-02")

	if param.Ctype == 5 {
		//获取上周返佣
		query1 = "select uid,sum(daily_bet_return) last_week_commi from tbl_report_user_daily where " + " created_at>='" + dailyStart + "' group by uid"
		//获取上周未领取返佣
		query2 = "select uid,daily_bet_return last_week_uncommi from tbl_member_return"
		//获取已领取返佣
		query3 = "select uid,daily_bet_return receive_commi from tbl_member_accu"

		//获取本周投注
		query4 = "select uid,sum(valid_waged) this_week from tbl_report_user_daily where " + " created_at>='" + dailyStart + "' group by uid"
		//获取上周投注
		query5 = "select uid,sum(valid_waged) last_week from tbl_report_user_daily where " + " created_at>='" + lastDailyStartDate + "' and created_at<'" + dailyStart + "' group by uid"
	}
	query := "select mb.uid,mb.operator_id,mb.business_id,ifnull(aa.last_week_commi,0) last_week_commi,ifnull(bb.last_week_uncommi,0) last_week_uncommi,ifnull(cc.receive_commi,0) receive_commi ,ifnull(dd.this_week,0) this_week,ifnull(ee.last_week,0) last_week from " + table + " as mb " +
		" left join (" + query1 + ") as aa on aa.uid=mb.uid" +
		" left join (" + query2 + ") as bb on bb.uid=mb.uid" +
		" left join (" + query3 + ") as cc on cc.uid=mb.uid" +
		" left join (" + query4 + ") as dd on dd.uid=mb.uid" +
		" left join (" + query5 + ") as ee on ee.uid=mb.uid"

	queryTable := "(" + query + " where mb.tester=1 )"

	if param.Uid != 0 {
		where += " and a.uid=" + strconv.Itoa(param.Uid)
	}

	if param.OderBY != "" {
		oderBy = param.OderBY
	}
	if param.OderType != "" {
		oderType = param.OderType
	}

	loginUser := GetLoginUser(ctx)
	if loginUser.Operator != "" {
		where += " and c.id=" + loginUser.Operator
	}
	if loginUser.Businsess != "" {
		where += " and d.id=" + loginUser.Businsess
	}

	join := " left join tbl_operator_info as c on c.id=a.operator_id" //渠道表
	join += " left join tbl_business_info as d on d.id=a.business_id" //业务员表

	order := oderBy + " " + oderType

	offset := (param.Page - 1) * param.PageSize
	if param.Page >= 1 {
		count := "select count(1) from " + table + " as a " + join + " where a.tester=1 and " + where
		err := meta.MerchantDB.Get(&data.T, count)
		if err != nil {

			return data, pushLog(fmt.Errorf("%s,[%s]", err.Error(), count), "数据库错误")
		}

		if data.T == 0 {
			return data, nil
		}
	}
	field := "a.uid,a.operator_id,a.business_id," +
		"(a.last_week_commi + a.last_week_uncommi) last_week_commi," +
		"(a.receive_commi + a.last_week_uncommi) total_commi," +
		"a.receive_commi,"
	if param.Ctype == 3 {
		field += "ifnull(a.this_week,CONCAT(0.00,'/',0.00)) this_week," +
			"ifnull(a.last_week,CONCAT(0.00,'/',0.00)) last_week"
	} else {
		field += "this_week,last_week"
	}

	query = "select " + field + " from " + queryTable + "  as a " + join + " where " + where + " order by " + order + " limit " + strconv.Itoa(param.PageSize) + " offset " + strconv.Itoa(offset)

	err := meta.MerchantDB.Select(&data.D, query)
	if err != nil && err != sql.ErrNoRows {

		return data, pushLog(fmt.Errorf("%s,[%s]", err.Error(), query), "数据库错误")
	}

	if err != nil && err != sql.ErrNoRows {
		return data, pushLog(fmt.Errorf("%s,[%s]", err.Error(), query), "数据库错误")
	}
	return data, nil
}

func RunningComiList(param RunningCommiParam, ctx *fasthttp.RequestCtx) (RunningCommiRetData, error) {
	data := RunningCommiRetData{}

	where := "1=1"
	oderBy := "a.created_at"
	oderType := "desc"

	if param.Uid != "" {
		where += " and a.uid=" + param.Uid
	}
	if param.SuperiorId != "" {
		where += " and a.superior_id=" + param.SuperiorId
	}
	if param.StartTime != "" {
		where += " and a.created_at>='" + param.StartTime + "'"
	}
	if param.EndTime != "" {
		where += " and a.created_at<='" + param.EndTime + "'"
	}

	if param.OderBY != "" {
		oderBy = param.OderBY
	}
	if param.OderType != "" {
		oderType = param.OderType
	}
	loginUser := GetLoginUser(ctx)
	if loginUser.Operator != "" {
		where += " and b.operator_id=" + loginUser.Operator
	} else if loginUser.Businsess != "" {
		where += " and b.business_id=" + loginUser.Businsess
	}

	if param.OderBY != "" {
		oderBy = param.OderBY
	}
	if param.OderType != "" {
		oderType = param.OderType
	}
	order := oderBy + " " + oderType

	table := "tbl_record_proxy_waged_return"
	join := " left join tbl_member_base as  b on b.uid=a.uid" //玩家表

	offset := (param.Page - 1) * param.PageSize
	if param.Page >= 1 {
		count := "select count(1) from " + table + " as a " + join + " where " + where

		err := meta.MerchantDB.Get(&data.T, count)
		if err != nil {

			return data, pushLog(fmt.Errorf("%s,[%s]", err.Error(), count), "数据库错误")
		}

		if data.T == 0 {
			return data, nil
		}
	}
	field := "a.*,b.business_id,b.operator_id"
	query := "select " + field + "  from " + table + " as a " + join + " where " + where + " order by " + order + " limit " + strconv.Itoa(param.PageSize) + " offset " + strconv.Itoa(offset)

	err := meta.MerchantDB.Select(&data.D, query)

	if err != nil && err != sql.ErrNoRows {
		return data, pushLog(fmt.Errorf("%s,[%s]", err.Error(), query), "数据库错误")
	}
	//统计
	sfield := "ifnull(sum(a.waged_commi),0) waged_commi"
	query = "select " + sfield + " from " + table + " as a " + join + " where " + where

	err = meta.MerchantDB.Get(&data.S, query)

	if err != nil && err != sql.ErrNoRows {
		return data, pushLog(fmt.Errorf("%s,[%s]", err.Error(), query), "数据库错误")
	}
	return data, nil
}

func DivideDepositList(param DivideDepositParam, ctx *fasthttp.RequestCtx) (DivideDepositRetData, error) {
	data := DivideDepositRetData{}

	where := "a.state=1"
	oderBy := "a.create_at"
	oderType := "desc"

	if param.Uid != "" {
		where += " and a.uid=" + param.Uid
	}
	if param.ParentId != "" {
		where += " and a.parent_id=" + param.ParentId
	}
	if param.Level != "" {
		where += " and a.level=" + param.Level
	}
	if param.StartTime != "" {
		StartTime, _ := helper.TimeToLoc(param.StartTime, loc)
		where += " and a.create_at>='" + strconv.FormatInt(StartTime, 10) + "'"
	}
	if param.EndTime != "" {
		EndTime, _ := helper.TimeToLoc(param.EndTime, loc)
		where += " and a.create_at<='" + strconv.FormatInt(EndTime, 10) + "'"
	}

	if param.OderBY != "" {
		oderBy = param.OderBY
	}
	if param.OderType != "" {
		oderType = param.OderType
	}
	loginUser := GetLoginUser(ctx)
	if loginUser.Operator != "" {
		where += " and b.operator_id=" + loginUser.Operator
	} else if loginUser.Businsess != "" {
		where += " and b.business_id=" + loginUser.Businsess
	}

	if param.OderBY != "" {
		oderBy = param.OderBY
	}
	if param.OderType != "" {
		oderType = param.OderType
	}
	order := oderBy + " " + oderType

	table := "tbl_rec_recharge_share"
	join := " left join tbl_member_base as  b on b.uid=a.uid" //玩家表

	offset := (param.Page - 1) * param.PageSize
	if param.Page >= 1 {
		count := "select count(1) from " + table + " as a " + join + " where " + where

		err := meta.MerchantDB.Get(&data.T, count)
		if err != nil {

			return data, pushLog(fmt.Errorf("%s,[%s]", err.Error(), count), "数据库错误")
		}

		if data.T == 0 {
			return data, nil
		}
	}
	field := "a.*,b.business_id,b.operator_id"
	query := "select " + field + "  from " + table + " as a " + join + " where " + where + " order by " + order + " limit " + strconv.Itoa(param.PageSize) + " offset " + strconv.Itoa(offset)

	err := meta.MerchantDB.Select(&data.D, query)

	if err != nil && err != sql.ErrNoRows {
		return data, pushLog(fmt.Errorf("%s,[%s]", err.Error(), query), "数据库错误")
	}
	//统计
	sfield := "ifnull(sum(a.amount),0) amount," +
		"ifnull(sum(a.recharge_share),0) recharge_share"
	query = "select " + sfield + " from " + table + " as a " + join + " where " + where

	err = meta.MerchantDB.Get(&data.S, query)

	if err != nil && err != sql.ErrNoRows {
		return data, pushLog(fmt.Errorf("%s,[%s]", err.Error(), query), "数据库错误")
	}
	return data, nil
}

func FirstDepositList(param DivideDepositParam, ctx *fasthttp.RequestCtx) (FisrtDepositRetData, error) {
	data := FisrtDepositRetData{}

	where := "a.state=1"
	oderBy := "a.create_at"
	oderType := "desc"

	if param.Uid != "" {
		where += " and a.uid=" + param.Uid
	}
	if param.ParentId != "" {
		where += " and a.parent_id=" + param.ParentId
	}
	if param.Level != "" {
		where += " and a.level=" + param.Level
	}
	if param.StartTime != "" {
		StartTime, _ := helper.TimeToLoc(param.StartTime, loc)
		where += " and a.create_at>='" + strconv.FormatInt(StartTime, 10) + "'"
	}
	if param.EndTime != "" {
		EndTime, _ := helper.TimeToLoc(param.EndTime, loc)
		where += " and a.create_at<='" + strconv.FormatInt(EndTime, 10) + "'"
	}

	if param.OderBY != "" {
		oderBy = param.OderBY
	}
	if param.OderType != "" {
		oderType = param.OderType
	}
	loginUser := GetLoginUser(ctx)
	if loginUser.Operator != "" {
		where += " and b.operator_id=" + loginUser.Operator
	} else if loginUser.Businsess != "" {
		where += " and b.business_id=" + loginUser.Businsess
	}

	if param.OderBY != "" {
		oderBy = param.OderBY
	}
	if param.OderType != "" {
		oderType = param.OderType
	}
	order := oderBy + " " + oderType

	table := "tbl_rec_first_deposit_bonus"
	join := " left join tbl_member_base as  b on b.uid=a.uid" //玩家表

	offset := (param.Page - 1) * param.PageSize
	if param.Page >= 1 {
		count := "select count(1) from " + table + " as a " + join + " where " + where

		err := meta.MerchantDB.Get(&data.T, count)
		if err != nil {

			return data, pushLog(fmt.Errorf("%s,[%s]", err.Error(), count), "数据库错误")
		}

		if data.T == 0 {
			return data, nil
		}
	}
	field := "a.*,b.business_id,b.operator_id"
	query := "select " + field + "  from " + table + " as a " + join + " where " + where + " order by " + order + " limit " + strconv.Itoa(param.PageSize) + " offset " + strconv.Itoa(offset)

	err := meta.MerchantDB.Select(&data.D, query)

	if err != nil && err != sql.ErrNoRows {
		return data, pushLog(fmt.Errorf("%s,[%s]", err.Error(), query), "数据库错误")
	}
	//统计
	sfield := "ifnull(sum(a.amount),0) amount," +
		"ifnull(sum(a.bonus),0) bonus"
	query = "select " + sfield + " from " + table + " as a " + join + " where " + where

	err = meta.MerchantDB.Get(&data.S, query)

	if err != nil && err != sql.ErrNoRows {
		return data, pushLog(fmt.Errorf("%s,[%s]", err.Error(), query), "数据库错误")
	}
	return data, nil
}

func Statistics(ctx *fasthttp.RequestCtx) (ReportGameStatisticsData, error) {
	data := ReportGameStatisticsData{}
	data.Running, _ = strconv.ParseFloat(meta.MerchantRedis.HGet(ctx, "PlatformRun", "PlayerTotalBet").Val(), 64)
	data.GameWinlost, _ = strconv.ParseFloat(meta.MerchantRedis.HGet(ctx, "PlatformRun", "PlayerTotalWin").Val(), 64)
	data.SystemProfit = data.GameWinlost - data.Running
	return data, nil
}

func PiggyBankList(param PiggyBankParam, ctx *fasthttp.RequestCtx) (PiggyBankRetData, error) {
	data := PiggyBankRetData{}

	where := "(a.amount>0 || a.interest>0 || total_interest>0)"
	oderBy := "a.id"
	oderType := "desc"

	if param.Uid != "" {
		where += " and a.uid=" + param.Uid
	}

	//if param.StartTime != "" {
	//	StartTime, _ := helper.TimeToLoc(param.StartTime, loc)
	//	where += " and a.interest_calc_time>='" + strconv.FormatInt(StartTime, 10) + "'"
	//}
	//if param.EndTime != "" {
	//	EndTime, _ := helper.TimeToLoc(param.EndTime, loc)
	//	where += " and a.interest_calc_time<='" + strconv.FormatInt(EndTime, 10) + "'"
	//}

	if param.OderBY != "" {
		oderBy = param.OderBY
	}
	if param.OderType != "" {
		oderType = param.OderType
	}
	loginUser := GetLoginUser(ctx)
	if loginUser.Operator != "" {
		where += " and b.operator_id=" + loginUser.Operator
	} else if loginUser.Businsess != "" {
		where += " and b.business_id=" + loginUser.Businsess
	}

	if param.OderBY != "" {
		oderBy = param.OderBY
	}
	if param.OderType != "" {
		oderType = param.OderType
	}
	order := oderBy + " " + oderType

	table := "tbl_member_piggy_bank"
	join := " left join tbl_member_base as  b on b.uid=a.uid" //玩家表

	offset := (param.Page - 1) * param.PageSize
	if param.Page >= 1 {
		count := "select count(1) from " + table + " as a " + join + " where " + where

		err := meta.MerchantDB.Get(&data.T, count)
		if err != nil {

			return data, pushLog(fmt.Errorf("%s,[%s]", err.Error(), count), "数据库错误")
		}

		if data.T == 0 {
			return data, nil
		}
	}
	field := "a.id,a.uid,a.amount,a.interest,a.total_interest"
	query := "select " + field + "  from " + table + " as a " + join + " where " + where + " order by " + order + " limit " + strconv.Itoa(param.PageSize) + " offset " + strconv.Itoa(offset)

	err := meta.MerchantDB.Select(&data.D, query)

	if err != nil && err != sql.ErrNoRows {
		return data, pushLog(fmt.Errorf("%s,[%s]", err.Error(), query), "数据库错误")
	}
	//统计
	sfield := "ifnull(sum(a.amount),0) amount," +
		"ifnull(sum(a.total_interest),0) total_interest," +
		"ifnull(sum(a.interest),0) interest"
	query = "select " + sfield + " from " + table + " as a " + join + " where " + where

	err = meta.MerchantDB.Get(&data.S, query)

	if err != nil && err != sql.ErrNoRows {
		return data, pushLog(fmt.Errorf("%s,[%s]", err.Error(), query), "数据库错误")
	}
	return data, nil
}

func UpdatePiggyBank(param PiggyBankParam, ctx *fasthttp.RequestCtx) error {
	data := PiggyBankData{}

	query := fmt.Sprintf("select id,uid,amount from tbl_member_piggy_bank where id=%d", param.Id)

	err := meta.MerchantDB.Get(&data, query)
	if err != nil {
		fmt.Println(err)
		return errors.New("数据库错误")
	}
	if data.Amount > 0 {
		query, _, _ := dialect.Update("tbl_member_piggy_bank").Set(g.Record{"interest": 0}).Where(g.Ex{"id": param.Id}).ToSQL()
		_, err := meta.MerchantDB.Exec(query)
		if err != nil {
			return errors.New("数据库错误")
		}

		//更新缓存
		if myredis.IsUserExis(data.Uid) {
			ret := myredis.SetUserFieldValue(data.Uid, "tbl_member_piggy_bank:interest", "0")
			if ret == false {
				return errors.New(helper.ServerErr)
			}
		}
	}

	return nil
}

type GettotaldataParam struct {
	Ttoken       string `json:"ttoken"`        //token
	MonthDate    string `json:"month_date"`    //月份 Y-m 格式
	OperatorId   string `json:"operator_id"`   //
	OperatorName string `json:"operator_name"` //
	StartTime    string `json:"start_time"`    // 查询开始时间
	EndTime      string `json:"end_time"`      // 查询结束时间
}
type GetTotalData struct {
	D1 OperatorInfo       `cbor:"d1" json:"d1"`
	D2 []ReportApiFeeData `cbor:"d2" json:"d2"`
	D3 []ReportDailyData  `cbor:"d3" json:"d3"`
}

func Gettotaldata(param GettotaldataParam, ctx *fasthttp.RequestCtx) (GetTotalData, error) {
	data := GetTotalData{}
	data.D1 = GetOperatorInfoName(param.OperatorName)
	if data.D1.Id == "" {
		return data, nil
	}

	monthDate := param.MonthDate
	if param.MonthDate == "" {
		monthDate = time.Now().Format("2006-01")
	}
	fromDate := monthDate + "-01"
	toDate := GetMonthStartAndEnd(monthDate)
	param2 := ReportApiFeeParam{}
	param2.OperatorId = (data.D1).Id
	param2.Page = 1
	param2.PageSize = 9999999
	data2 := reportOperatorApiFeeList(param2, fromDate, toDate, "")
	data.D2 = data2.D
	if param.MonthDate != "" {
		return data, nil
	}
	param3 := ReportDailyParam{}
	param3.OperatorId = (data.D1).Id
	param3.IsOperator = 1
	param3.StartTime = param.StartTime
	param3.EndTime = param.EndTime
	param3.Page = 1
	param3.PageSize = 9999999
	param3.OderBY = "created_at"
	param3.OderType = "asc"
	data3, _ := ReportPlatformDailyList(param3, ctx)
	data.D3 = data3.D

	return data, nil
}
